// 投票的公共方法mixin
import { getBindInfo, getVoteDetail, voteAdd, resendVoteAdd, recordCheck } from '@/api/index'
import {objectToParams} from '@/util/function'
import ls from '@/util/ls'
import dayjs from 'dayjs'
import applyforactiviation from '@/static/applyforactiviation.png'

export default {
  data() {
    return {
      isLoading: true,
      scrollTop: 0,
      isSubmitting: false, // 防止重复提交的状态
      isRevote: false, // 是否是重新投票状态
      formData: {
        houseId: '',
        voteSign: '',
        optionId: '',
        voteId: '',
        liveUserId: '',
        communityId: ''
      },
      houseList: [],
      voteInfo: {},
      VotingratioInfo: {},
      optionInfo: {
        zongvoteNum: 0,
        zongvoteSize: 0,
        voteRule: -1 // 2,4为多选 1,3为单选
      },
      pmsVoteOptions: [],
      // pmsVoteOptionMap: {}, // 添加多问题数据结构
      isClick: false,
      votedHouseIds: [],
      houseCheckResult: {
        successHouse: [], // 未投票的房屋
        failedHouse: []   // 已投票的房屋
      },
      isFromRelatedHouses: false, // 是否从关联房屋页面返回
      isVotingInfo: {
        isVoting: false, // 自己是否投票
        voteId: 0,
        optionId: [],
        houseId: "",
        createDate: "",
        status: 1, // 0投票结束 1投票中 2投票未开始 4没有绑定成功的房子
        voteSign: "",
        voteRule: -1,
        recordId: 0
      },
      options: {},
      nvtoStatus: 0, // 1跳转签名
      houseId: "",
      isFirstPage: false
    }
  },

  watch: {
    formData: {
      handler(newVal) {
        this.updateIsClick()
      },
      deep: true
    }
  },

  computed: {
    isChooseAHouse() {
      let status = this.isVotingInfo.status
      let isVoting = this.isVotingInfo.isVoting
      if (status == 0 && !isVoting) {
        return false
      } else if (status == 2) {
        return false
      }
      return true
    },
    isSignature() {
      let status = this.isVotingInfo.status
      let isVoting = this.isVotingInfo.isVoting
      if (status == 0 && !isVoting) { // 结束了 没有签名的
        return false
      } else if (status == 2) { // 未开始
        return false
      }
      return true
    }
  },

  onLoad(options) {
    this.isLoading = true
    this.options = options

  },

  onShow() {
    if (this.nvtoStatus == 1) {
      this.nvtoStatus = 0
      return
    }
    setTimeout(() => {
      this.init(this.options)
    }, 50)
  },

  onPageScroll(e) {
  
    this.scrollTop = e.scrollTop
  },

  methods: {
    share(){
      let type=this.options.type
      let title=this.voteInfo.voteTitle
    
      let path=""
      let params=objectToParams({
        voteId:this.formData.voteId,
        communityId:this.formData.communityId,
        wxUserId:this.formData.liveUserId,
        type:type
      }) 
      if(type==1){
        path=`/pages/votingForm/index?${params}`
      }else if(type==2){  
        path=`/pages/quickresolution/index?${params}`
      }else if(type==3){
        path=`/pages/questionnaire/index?${params}`
      }else if(type==4){
          path=`/pages/initiative/index?${params}`
        }
      return {
        title,
        path,
       
      }
    },
    // 更新isClick状态 - 子类可以重写此方法
    updateIsClick() {
      let fromdata = this.formData
      if (fromdata.voteSign) {
        this.isClick = true
      } else {
        this.isClick = false
      }
    },

    // 解析scene参数的函数
    parseSceneParams(options) {
      if (options.scene) {
        try {
          // 解码scene参数
          const decodedScene = decodeURIComponent(options.scene)
          
          // 使用原生字符串解析方法替代URLSearchParams
          const params = {}
          const queryString = decodedScene
          const pairs = queryString.split('&')
          
          for (let pair of pairs) {
            const [key, value] = pair.split('=')
            if (key && value) {
              params[key] = value
            }
          }
          
          const voteId = params.voteId
          const communityId = params.communityId
          
          if (voteId) {
            options.voteId = voteId
          }
          if (communityId) {
            options.communityId = communityId
          }
          
          return { voteId, communityId }
        } catch (error) {
          console.error("解析scene参数失败:", error)
        }
      }
    },

    goToSign() {
      this.nvtoStatus = 1
    },

    login() {
      return new Promise((resolve, reject) => {
        let token = ls.get("token")
        if (!token) {
          uni.navigateTo({
            url: "/pages/login/index?login=2"
          })
        }
      })
    },

    handleClick() {
      let fromdata = JSON.parse(JSON.stringify(this.formData))
      fromdata.optionList = this.formData.optionId
      fromdata.optionId = undefined
      fromdata.voteId = Number(fromdata.voteId)
      fromdata.recodeType="1"
      
      if (this.houseList && this.houseList.length > 0) {
        fromdata.houseId = this.houseList[0].houseId
      } else {
        uni.showModal({
          title: "提示",
          content: "您还没有绑定房屋，请先绑定房屋",
          success: () => {
            uni.switchTab({
              url: "/pages/home/index"
            })
          }
        })
        return
      }

      this.formData.houseId = ""
      this.formData.voteSign = ""
      this.formData.optionId = ""
      fromdata.optionList = []
      
      voteAdd(fromdata).then(res => {
        this.methodGetVoteDetail()
      })
    },
    handleVoteAdd(fromdata,type=1){
      fromdata.recordType=1
     
      // 根据 isRevote 判断调用哪个接口
      const voteApiCall = this.isRevote ? resendVoteAdd(fromdata) : voteAdd(fromdata)
      
      return voteApiCall.then(res => {
        if(res.code==200){
         if(type==2){
             this.formData.houseId = ""
            this.formData.voteSign = ""
            this.formData.optionId = ""
         }
          // 重新投票成功后，重置 isRevote 状态
          if(this.isRevote) {
            this.isRevote = false
          }
          
          this.methodGetVoteDetail()
          this.showVoteSuccessModal()
        }else{
          uni.showToast({
            title: res.msg,
            icon: "none"
          })
        } 
      }).catch(error => {
        console.error('投票提交失败:', error)
        uni.showToast({
          title: '提交失败，请重试',
          icon: "none"
        })
      })
    },
    getCurrentpage(options) { // 分享或者扫码打开的
      console.log("option",options)
      let pages = getCurrentPages()
      let len = pages.length
      
      if (len == 1) {
        this.$store.commit("community/setCommunityId", options.communityId)
      }
      this.isFirstPage = (len === 1)
    },

    async init(options) {
      if (options.scene) {  // 扫码进来的 处理scene参数，如果存在则解析其中的voteId和communityId
        options = this.parseSceneParams(options)
        this.getCurrentpage(options)
      }  else if(options.communityId&&this.$store.state.community.communityId==-1){ //分享进来的
        this.getCurrentpage(options)
      } 

    
      let token = ls.get("token")
      let user = this.$store.state.app.user
      if (user && user.wxUser) {
        options["wxUserId"] = user.wxUser.wxUserId
      }
      if (!token) {
        await this.login()
        
        let t = setTimeout(() => {
          this.setParams(options)
          clearTimeout(t)
        }, 1000)
      } else {
        this.setParams(options)
      }
    },

    async setParams(options) {
      this.formData.voteId = options.voteId
      this.formData.liveUserId = options.wxUserId
      this.formData.communityId = options.communityId
      
      this.$nextTick(() => {
        this.getVoteList()
        this.methodGetVoteDetail()
       
      })
    },

    async getVoteList() {
      let data2 = await getBindInfo({
        communityId: this.formData.communityId,
        wxUserId: this.formData.liveUserId,
        auditStatus: 2
      })
      this.$store.commit("community/setBoundHouses", data2.rows.length)
    },

    selectHouse(house) {
      try {
        this.isVotingInfo.houseId = house.id
        this.houseId = house.id
        
        this.verifyHouse(house.id)
        this.formData.houseId = house.id
      } catch (error) {
        console.error('选择房屋失败:', error)
      }
    },

    verifyHouse(houseId) {
      let row = this.votedHouseIds.find(item => item.houseId == houseId)
      
      if (row) {
        this.setIsVotingInfo(row)
      } else {
        this.isVotingInfo = {
          isVoting: false,
          voteId: 0,
          optionId: [],
          houseId: 0,
          createDate: "",
          status: 1,
          voteSign: ""
        }
        // 子类可以重写此方法来自定义选项处理逻辑
        this.handleOptionSelection()
      }
    },

    // 处理选项选择 - 子类可以重写此方法
    handleOptionSelection() {
      if (this.$refs.voteFrom && this.$refs.voteFrom.getSelectedIndex) {
        let indx = this.$refs.voteFrom.getSelectedIndex()
        if (indx.length >= 0) {
          this.formData.optionId = indx
        }
      }
    },

    // 获取议题的选择限制（min/max）
    getQuestionSelectionLimit(questionTitle) {
      if (!this.pmsVoteOptions || this.pmsVoteOptions.length === 0) {
        return { min: 0, max: 999 }
      }
      
      // 查找对应议题的选项
      const questionOption = this.pmsVoteOptions.find(option => 
        option.title === questionTitle || option.questionTitle === questionTitle
      )
      
      if (questionOption) {
        return {
          min: questionOption.min || 0,
          max: questionOption.max || 999
        }
      }
      
      return { min: 0, max: 999 }
    },

    // 检查议题选择数量是否符合限制
    validateQuestionSelection(questionTitle, selectedCount) {
      const limit = this.getQuestionSelectionLimit(questionTitle)
      return {
        isValid: selectedCount >= limit.min && selectedCount <= limit.max,
        min: limit.min,
        max: limit.max,
        current: selectedCount
      }
    },

    // 获取所有议题的选择验证结果
    getAllQuestionsValidation() {
      if (!this.$refs.voteFrom || !this.$refs.voteFrom.groupedOptions) {
        return { isValid: true, details: [] }
      }
      
      const groupedOptions = this.$refs.voteFrom.groupedOptions
      const questionTitles = Object.keys(groupedOptions)
      const validationResults = []
      let allValid = true
      
      for (let questionTitle of questionTitles) {
        const questionOptions = groupedOptions[questionTitle] || []
        const questionOptionIds = questionOptions.map(option => String(option.optionId))
        
        // 获取当前议题的选中选项数量
        const selectedOptions = this.$refs.voteFrom.getSelectedIndex() || []
        const currentQuestionSelectedCount = selectedOptions.filter(selectedOption => 
          questionOptionIds.includes(String(selectedOption.optionId))
        ).length
        
        const validation = this.validateQuestionSelection(questionTitle, currentQuestionSelectedCount)
        validationResults.push({
          questionTitle,
          ...validation
        })
        
        if (!validation.isValid) {
          allValid = false
        }
      }
      
      return {
        isValid: allValid,
        details: validationResults
      }
    },

    setIsVotingInfo(row) {

      this.isVotingInfo.recordId = row.recordId
      
      let voteOptionIds = JSON.parse(row.voteOptionId)
      if (voteOptionIds.length == 1) {
        this.isVotingInfo.optionId = JSON.parse(row.voteOptionId)[0]
      } else {
        this.isVotingInfo.optionId = JSON.parse(row.voteOptionId).map(e => Number(e))
      }
      this.isVotingInfo.isVoting = true
      this.isVotingInfo.voteId = row.voteId
      this.isVotingInfo.houseId = row.houseId
      this.isVotingInfo.createDate = row.createDate
      this.isVotingInfo.voteSign = row.voteSign
    },

    uploadSign(res) {
      this.formData.voteSign = res
    },

    handleTime(startDate, endDate) {
      let now = dayjs()
      let start = dayjs(startDate)
      let end = dayjs(endDate)
      
      let status = 0
      if (now.isBefore(start)) {
        status = 2 // 未开始
      } else if (now.isAfter(end)) {
        status = 0 // 已结束
      } else {
        status = 1 // 进行中
      }
      return status
    },

    async methodGetVoteDetail() {
      let datas = await getVoteDetail({
        voteId: this.formData.voteId.toString(),
        userId: this.formData.liveUserId,
        communityId: this.formData.communityId.toString()
      })
      let data = datas.data
      
      try {
        let pmsVoteRecords = data.pmsVoteRecords
        console.log("pmsVoteRecords",pmsVoteRecords)
        let pmsVote = data.pmsVote
        
        this.isVotingInfo.status = this.handleTime(pmsVote.startDate, pmsVote.endDate)
        this.isLoading = false
        
        if (pmsVoteRecords && pmsVoteRecords.length > 0) {
          let houseId = this.houseId
          let pmsVoteRecordszero = null
          
          if (houseId !== "") {
            pmsVoteRecordszero = pmsVoteRecords.find(item => item.houseId == houseId)
          } else {
            pmsVoteRecordszero = pmsVoteRecords[0]
          }
          
          if(pmsVoteRecordszero){
            this.setIsVotingInfo(pmsVoteRecordszero)
          }
        
        } else {
          this.isVotingInfo.isVoting = false
          this.isVotingInfo.houseId = ''
        }
        
        this.voteInfo = data.pmsVote
        
        let sumVoteTotalPerson = data.sumVoteTotalPerson || 0
        let sumTotalSize = data.sumTotalSize || 0
        let sumVoteTotalSize = data.sumVoteTotalSize || 0
        // sumTotalPerson 总人数   sumVoteTotalPerson 投票总人数  
        // sumTotalSize 总面积  sumVoteTotalSize 投票总面积
        console.log("sumVoteTotalPerson",sumVoteTotalPerson,data.sumTotalPerson,((sumVoteTotalPerson / data.sumTotalPerson)*100).toFixed(2))
        this.VotingratioInfo = {
          already: data.sumVoteTotalPerson || 0,
          alreadyproportion: ((sumVoteTotalPerson / data.sumTotalPerson)*100).toFixed(2) + "%",
          personproportion: ((  sumVoteTotalSize/ sumTotalSize)*100).toFixed(2) + "%",
          sumTotalSize:sumTotalSize,
          sumVoteTotalSize: sumVoteTotalSize || 0,
          sumTotalPerson: data.sumTotalPerson,
        }
        
        let pmsVoteOptions = data.pmsVoteOptions
        console.log("pmsVoteOptions",pmsVoteOptions)
       this.pmsVoteOptions=pmsVoteOptions
      
        


        let zongvoteNum = pmsVoteOptions.reduce((total, item) => total + item.voteNum, 0)
        let zongvoteSize = pmsVoteOptions.reduce((total, item) => total + item.areaNum, 0)
        
        this.optionInfo = {
          zongvoteNum,
          zongvoteSize,
          voteRule: pmsVote.voteRule
        }
        
        // 检查是否从关联房屋页面返回
        const fromRelatedHouses = uni.getStorageSync('fromRelatedHouses')
        // 保存状态供其他地方使用
        this.isFromRelatedHouses = !!fromRelatedHouses
        
        // 判断是否已投票，决定使用哪个房屋列表
        if (pmsVoteRecords && pmsVoteRecords.length > 0) {
          // 已投票的情况
          const votedHousesCount = data.votedHouses?.length || 0
          const allHousesCount = data.pmsHouses?.length || 0
          
          // 如果从关联房屋页面返回，且房屋数量不一致，允许重新投票
          if (fromRelatedHouses && votedHousesCount < allHousesCount) {
            console.log('从关联房屋页面返回，检测到房屋数量变化，允许重新投票')
            
            // 使用所有已绑定的房屋列表
            this.houseList = data.pmsHouses || []
            
            // 保存已投票的房屋列表（用于标记新增房屋）
            this.votedHouseIds = data.votedHouses || []
            
            console.log('重新投票数据:', {
              allHouses: this.houseList.map(h => h.houseId),
              votedHouses: this.votedHouseIds.map(h => h.houseId),
              allCount: this.houseList.length,
              votedCount: this.votedHouseIds.length
            })
            
            // 设置为重新投票状态
            this.isRevote = true
            
            // 保留第一次的投票选项（不重置，禁用修改）
            if (pmsVoteRecords[0]) {
              let voteOptionIds = JSON.parse(pmsVoteRecords[0].voteOptionId)
              this.isVotingInfo.optionId = voteOptionIds
              
              // 将 optionId 转换为对象数组格式（与首次投票保持一致）
              const optionList = voteOptionIds.map(optionId => {
                // 从 pmsVoteOptions 中找到对应的选项信息
                const option = pmsVoteOptions.find(opt => String(opt.optionId) === String(optionId))
                return option || { optionId: optionId }
              })
              
              this.formData.optionId = optionList  // 设置为对象数组
              this.isVotingInfo.recordId = pmsVoteRecords[0].recordId
            }
            
            // 重置投票状态（但保留选项）
            this.isVotingInfo.isVoting = false
            this.isVotingInfo.houseId = ''
            this.isVotingInfo.voteSign = '' // 清空签名，需要重新签名
            
            // 清空表单签名（需要重新签名）
            this.formData.houseId = ''
            this.formData.voteSign = ''
            
            // 清除缓存标记
            uni.removeStorageSync('fromRelatedHouses')
            
            // 先不提示，等调用 checkVoteRecord 后再判断是否有未投票的新增房屋
          } else {
            // 正常已投票流程：使用已投票的房屋列表
            this.houseList = data.votedHouses || []
            this.votedHouseIds = []
            this.isRevote = false
            
            // 清除缓存标记（如果有）
            uni.removeStorageSync('fromRelatedHouses')
          }
        } else {
          // 未投票：使用所有已绑定的房屋列表
          this.houseList = data.pmsHouses || []
          this.votedHouseIds = []
          
          // 清除缓存标记（如果有）
          uni.removeStorageSync('fromRelatedHouses')
        }
        
       if(!this.houseList || this.houseList.length === 0){  //如果没有审核成功的房子
        this.isVotingInfo.status=4
       }
        
        // 子类可以重写此方法来处理额外的数据
        this.handleAdditionalData(data)
        
        // 任何状态下都调用 pms/record/check 接口
        console.log('调用 pms/record/check 接口', {
          hasVoted: pmsVoteRecords && pmsVoteRecords.length > 0,
          fromRelatedHouses: !!fromRelatedHouses
        })
        await this.checkVoteRecord()
        
        // 只有未投票状态才使用 checkVoteRecord 的结果进行判定
        // 已投票状态下，houseCheckResult 会被调用但不会影响显示逻辑
        
        // 如果是从关联房屋返回且是重新投票状态，检查是否真的有未投票的新增房屋
        if (this.isRevote && this.isFromRelatedHouses && this.houseCheckResult) {
          // 获取所有房屋ID
          const allHouseIds = this.houseList.map(h => String(h.houseId))
          
          // 获取已投票的房屋ID
          const votedHouseIds = (this.houseCheckResult.failedHouse || []).map(item => 
            String(item.pmsHouse?.houseId)
          ).filter(id => id)
          
          // 找出未投票的房屋
          const unvotedHouseIds = allHouseIds.filter(id => !votedHouseIds.includes(id))
          
          console.log('新增房屋检查:', {
            allHouseIds,
            votedHouseIds,
            unvotedHouseIds,
            hasUnvotedHouses: unvotedHouseIds.length > 0
          })
          
          // 只有真的有未投票的新增房屋时才提示
          if (unvotedHouseIds.length > 0) {
            uni.showToast({
              title: `检测到${unvotedHouseIds.length}个新增房屋，请重新签名提交`,
              icon: 'none',
              duration: 2000
            })
          } else {
            // 所有房屋都已投票，提示已完成
            uni.showToast({
              title: '所有房屋均已投票',
              icon: 'none',
              duration: 2000
            })
          }
        }
        
      } catch (error) {
        console.log("error",error)
        uni.showModal({
          title: "提示",
          content: "该投票已经结束，请返回首页",
          success: () => {
            uni.switchTab({
              url: "/pages/home/index"
            })
          }
        })
      }
    },

    // 处理额外数据 - 子类可以重写此方法
    handleAdditionalData(data) {
      // 默认实现为空，子类可以重写
    },

    // 检查投票记录
    async checkVoteRecord() {
      try {
        // 准备与投票接口相同的参数
        let fromdata = JSON.parse(JSON.stringify(this.formData))
        // fromdata.optionList = this.formData.optionId
        fromdata.optionId = undefined
        fromdata.voteId = Number(fromdata.voteId)
        fromdata.recordType = 1
        fromdata.voteSign=undefined
        
        // 如果有房屋列表，取所有房屋ID
        if (this.houseList && this.houseList.length > 0) {
          let houseIds = this.houseList.map(item => item.houseId)
          fromdata.houseId = houseIds.join(',')
        }
        
        console.log('调用 pms/record/check 接口，参数:', fromdata)
        
        // 调用检查接口
        const res = await recordCheck(fromdata)
        
        console.log('pms/record/check 接口响应:', res)
        
        // 可以根据接口返回结果做进一步处理
        if (res && res.code === 200 && res.data) {
          // 检查成功的处理逻辑
          console.log('投票记录检查成功')
          
          // 保存房屋检查结果
          this.houseCheckResult = {
            successHouse: res.data.successHouse || [], // 未投票的房屋
            failedHouse: res.data.failedHouse || []    // 已投票的房屋
          }
          
          console.log('房屋检查结果:', this.houseCheckResult)
        }
        
        return res
      } catch (error) {
        console.error('检查投票记录失败:', error)
      }
    },

        // 投票成功弹框
    showVoteSuccessModal() {
      // 使用 uView Modal 组件显示投票成功弹框
      this.$refs.voteSuccessModal && this.$refs.voteSuccessModal.showModal()
    },

    // 显示投票成功弹框（内部方法）
    showModal() {
      if (this.$refs.voteSuccessModal) {
        this.$refs.voteSuccessModal.show = true
      }
    },

    // 投票成功确认后的处理 - 子类可以重写此方法
  
  }
} 